import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// Created by changlei on 2024/3/21.
///
/// 播放/暂停按钮
class PlayButton extends StatefulWidget {
  /// 播放/暂停按钮
  const PlayButton({
    super.key,
    required this.isPlaying,
    this.onPressed,
  });

  /// 是否正在播放
  final bool isPlaying;

  /// onPressed
  final VoidCallback? onPressed;

  @override
  State<PlayButton> createState() => _PlayButtonState();
}

class _PlayButtonState extends State<PlayButton> with SingleTickerProviderStateMixin {
  late final _controller = AnimationController(
    duration: const Duration(milliseconds: 300),
    vsync: this,
  );

  void _playOrPause() {
    if (widget.isPlaying) {
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

  @override
  void initState() {
    super.initState();
    _playOrPause();
  }

  @override
  void didUpdateWidget(covariant PlayButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isPlaying != oldWidget.isPlaying) {
      _playOrPause();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      minSize: 0,
      onPressed: widget.onPressed,
      child: AnimatedIcon(
        icon: AnimatedIcons.play_pause,
        progress: _controller,
      ),
    );
  }
}
